Tailwind CSS

Alignment and Spacing


Alignment and spacing refer to the methods and classes used to arrange elements within a layout and control the distance between them.

 

Alignment involves positioning elements horizontally and vertically within their containers, while spacing pertains to adjusting the distance between elements or between elements and their container boundaries. Tailwind provides a wide range of utility classes for achieving precise alignment and spacing, enabling developers to create visually appealing and well-structured user interfaces without the need for custom CSS.

 

Alignment

 

1. Horizontal Alignment:

 Use classes like justify-start, justify-center, justify-end, and justify-between to align items horizontally within a container.


2. Vertical Alignment:

Employ classes such as items-start, items-center, and items-end to align items vertically within a container.
 

3. Self Alignment: 

Apply self-start, self-center, and self-end to align individual items within a flex container.

 

Spacing

 

1. Margin:

Use classes like m-[size] to apply margin to all sides, or mx-[size], my-[size] for horizontal and vertical margin respectively. You can also specify margin for individual sides using classes like mt-[size], mr-[size], mb-[size], and ml-[size].


2. Padding:

Similar to margin, use classes like p-[size], px-[size], py-[size], pt-[size], pr-[size], pb-[size], and pl-[size] to apply padding to elements.


3. Negative Margin and Padding:

 Tailwind also supports negative margin and padding classes, allowing you to adjust spacing more precisely when needed.
 

3. Spacing Scale:

Tailwind provides a spacing scale in its default configuration, which you can use to apply consistent spacing throughout your project. For example, m-4 applies margin of 1rem based on the spacing scale defined in the configuration.

 

Example:

<div class="flex justify-between items-center">
   <div class="flex items-center">
       <div class="w-10 h-10 bg-blue-500"></div>
       <p class="ml-2">Left Aligned Item</p>
   </div>
   <p class="text-center">Center Aligned Item</p>
   <div class="flex items-center">
       <p class="mr-2">Right Aligned Item</p>
       <div class="w-10 h-10 bg-green-500"></div>
   </div>
</div>